package com.yanqu.road.server.cmd.player;

import com.yanqu.road.entity.player.*;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;

@Cmd(code = Protocol.S_WATCH_PLAYER, desc = "拜访玩家")
public class WatchPlayerCmd extends AbstractCommand {

	private long watchUserId;

	private long watchServerId;

	private WatchPlayerResult watchPlayerResult;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		PlayerProto.WatchPlayerReqMsg reqMsg = PlayerProto.WatchPlayerReqMsg.parseFrom(packet.getBytes());
		watchUserId = reqMsg.getUserId();
		watchServerId = reqMsg.getServerId();
		if(watchServerId == 0){
			watchServerId = GameServer.getInstance().getServerId();
		}
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(watchServerId == GameServer.getInstance().getServerId()) {//本服逻辑
			if (player.getUserId() == watchUserId) {
				return;
			}
			watchPlayerResult = UserMgr.watchPlayer(watchUserId);
		}else {//跨服逻辑
			PlayerProto.WatchPlayerReqMsg.Builder msg = PlayerProto.WatchPlayerReqMsg.newBuilder();
			msg.setUserId(watchUserId);
			msg.setServerId(watchServerId);
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_WATCH_PLAYER, msg);
			GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		if(watchServerId == GameServer.getInstance().getServerId()) {//本服逻辑
			//拜访简化
//			PlayerProto.WatchPlayerRespMsg.Builder respMsg = PlayerPb.parseWatchPlayerRespMsg(watchPlayerResult);
			PlayerProto.WatchPlayerSimpleRespMsg.Builder respMsg = PlayerPb.parseWatchPlayerSimpleRespMsg(watchPlayerResult);
			player.sendPacket(Protocol.U_WATCH_PLAYER, respMsg);
		}
	}
}
